package com.me.template4j.service.impl;

import com.me.template4j.exception.CustomException;
import com.me.template4j.pojo.FileBean;
import com.me.template4j.service.DFSService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DFSServiceImpl implements DFSService {

    @Value("${mydfs.sourceDir}")
    private String sourceDir;

    @Override
    public String saveFile(MultipartFile file, String projectName) throws CustomException, IOException {
        if (file.isEmpty()) {
            throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "上传失败");
        }
        String fileName = file.getOriginalFilename();

        String suffixName = "";
        if(fileName.lastIndexOf(".") == -1) {
            suffixName = "";
        }else {
            suffixName = fileName.substring(fileName.lastIndexOf("."));
        }
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDir = getFile(newFileName, projectName);
        file.transferTo(fileDir);

        return newFileName;
    }

    private File getFile(String fileName, String projectName) {
        File file = null;
        String filePath = sourceDir;

        if(!projectName.isBlank() && !projectName.isEmpty()) {
            filePath += "/"+projectName;
        }
        filePath += "/" + fileName;

        file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    @Override
    public List<FileBean> searchFile(String inputFileName, String projectName) {
        String filePath = sourceDir;

        if(!projectName.isBlank() && !projectName.isEmpty()) {
            filePath += "/"+projectName;
        }
        File folder = new File(filePath);

        FilenameFilter filenameFilter = (dir, name)
                -> inputFileName == null || inputFileName.isEmpty() || name.contains(inputFileName);
        File[] files = folder.listFiles(filenameFilter);;

        List<FileBean> array = new ArrayList<>();

        for (File file: files) {
            boolean hidden = file.isHidden();
            if(hidden) continue;
            // 不需要文件夹
            boolean directory = file.isDirectory();
            if(directory) continue;
            // 文件名
            String name = file.getName();
            // 文件大小
            long size = file.length();

            // 最近更新时间
            long updateTime = file.lastModified();
            FileBean fileBean = new FileBean();
            fileBean.setFileName(name);
            fileBean.setFileSize(size);
            fileBean.setUpdateTime(updateTime);

            array.add(fileBean);
        }

        array.sort((obj1,obj2)->{
            long l1 = obj1.getUpdateTime();
            long l2 = obj2.getUpdateTime();
            return Long.compare(l2, l1);
        });


        return array;
    }

    @Override
    public void deleteFile(String fileName, String projectName) throws CustomException {


        String filePath = sourceDir;

        if(!projectName.isBlank() && !projectName.isEmpty()) {
            filePath += "/"+projectName;
        }
        filePath += "/" + fileName;

        File file = new File(filePath);
        //路径是个文件且不为空时删除文件
        if(file.isFile() && file.exists()){
            file.delete();
        }else {
            throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR,"文件不存在");
        }
    }
}
